package com.fayuan.nocv.utils;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.UUID;

public class AliyunOSSUtil {

    private static final String accessKeyId= OssConstant.OSS_ACCESS_KEY_ID_IM;
    private static final String accessKeySecret=OssConstant.OSS_ACCESS_KEY_SECRET_IM;
    private static final String endpoint =  OssConstant.OSS_END_POINT_IM;
    private static final String bucket = OssConstant.OSS_BUCKET_IM;

    private static final Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);

    public static String uploadFileAvatar(MultipartFile file) {
        // 从工具类中获取对象
        String endpoint = OssConstant.OSS_END_POINT_IM;
        String accessKeyId = OssConstant.OSS_ACCESS_KEY_ID_IM;
        String accessKeySecret = OssConstant.OSS_ACCESS_KEY_SECRET_IM;
        String bucketName = OssConstant.OSS_BUCKET_IM;

        try {
            // 创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 获取上传文件的输入流
            InputStream inputStream = file.getInputStream();
            // 获取文件原始名称
            String filename = file.getOriginalFilename();
            // 完善1、 --> 在文件名中添加唯一值
            String uuid = UUID.randomUUID().toString().replace("-", "");
            filename = uuid + filename;
            // 完善2、 --> 把文件按照日期分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            // 拼接时间 yyyy/MM/dd/filename
            filename = datePath + "/" + filename;
            //System.out.println(filename);
            // 调用oss方法实现上传
            // 1、bucketName 2、上传到oss文件路径和文件名称 3、文件的输入流
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, filename, inputStream);
            String eTag = putObjectResult.getETag();
            // 获取url地址（根据阿里云oss中的图片实例拼接字符串） 拼接url字符串
            // https://edu-leader.oss-cn-beijing.aliyuncs.com/%E4%BB%96.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+filename;
            // 关闭oss
            ossClient.shutdown();
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}

